package com.gxa.autoparts.admin.realm;


import com.gxa.autoparts.admin.service.AdminService;
import com.gxa.autoparts.core.pojo.Admin;
import com.gxa.autoparts.core.pojo.Permission;
import com.gxa.autoparts.core.pojo.Role;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author xhy
 * @Date 2021/12/23 14:09
 */
@Repository
public class AdminRealm extends AuthorizingRealm {


    @Autowired
    AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        List<Role> roleList = adminService.getRoleList(name);
        System.out.println("------------\n"+roleList);
        //添加角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (Role role : roleList) {
            //添加角色
            info.addRole(role.getName());
            //添加权限
            for (Permission permissions : role.getPermissionList()) {
                info.addStringPermission(permissions.getName());
            }
        }
        return info;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (StringUtils.isEmpty(token.getPrincipal())) {
            try {
                throw new Exception("AuthenticationToken 不能为空");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        //获取用户信息
        String name = token.getPrincipal().toString();
        System.out.println("name:-------------\n"+name);
        Admin admin = adminService.selectByName(name);
        if (admin == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(name, admin.getPwd(), getName());
            return info;
        }
    }
}
